#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>

#include "sign_in_view.h"
#include "student_list_view.h"
#include "student_view.h"
#include "test_info_view.h"
#include "course_view.h"
#include "test_list_view.h"
#include "test_view.h"
#include "debug_view.h"
#include <algorithm>
#include <QDebug>

MainWindow* g_mainWindow;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    g_mainWindow = this;
    ui->setupUi(this);
    ui->mainToolBar->deleteLater();
//    ui->menuBar->deleteLater();
    ui->statusBar->deleteLater();
    centralWidget = new QWidget(this);
    mainItem = 0;

    onchangeScene(SIGN_IN_VIEW);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onchangeScene(ViewsEnum i){
    if (mainItem){
        mainItem->deleteLater();
    }
    if (centralWidget){
        centralWidget->deleteLater();
    }

    std::vector<ViewsEnum>::iterator it = std::find(history.begin(), history.end(), i);
    if (it != history.end())
    {
        history.erase(it,history.end());
    }

    if (i != SIGN_IN_VIEW && i != DEBUG_VIEW)
    {
        history.push_back(i);
    }

/*
    for (unsigned j = 0; j < history.size(); j++)
    {
        qDebug() << history[j];
    }
//*/

    centralWidget = new QWidget(this);
    switch (i){
    case SIGN_IN_VIEW:
        mainItem = new sign_in_view(centralWidget);
        break;
    case STUDENT_LIST_VIEW:
        mainItem = new student_list_view(centralWidget);
        break;
    case STUDENT_VIEW:
        mainItem = new student_view(centralWidget);
        break;
    case TEST_INFO_VIEW:
        mainItem = new test_info_view(centralWidget);
        break;
    case COURSE_VIEW:
        mainItem = new course_view(centralWidget);
        break;
    case TEST_LIST_VIEW:
        mainItem = new test_list_view(centralWidget);
        break;
    case TEST_VIEW:
        mainItem = new test_view(centralWidget);
        break;
    case DEBUG_VIEW:
        mainItem = new debug_view(centralWidget);
        break;
    default:
        setCentralWidget(centralWidget);
        return;
    }

    QObject::connect(mainItem,SIGNAL(changeScene(ViewsEnum)),
                     this,SLOT(onchangeScene(ViewsEnum)));
    setCentralWidget(centralWidget);

}

ViewsEnum MainWindow::getLastScene()
{
    if (history.size() >= 2)
    {
        return history[history.size() - 2];
    }
    else if (history.size() == 1)
    {
        return history.back();
    }
    else
    {
        return SIGN_IN_VIEW;
    }
}

bool MainWindow::hasHistory()
{
    return history.size() > 1;
}

ViewsEnum MainWindow::getCurrentScene()
{
    if (history.empty())
    {
        return SIGN_IN_VIEW;
    }
    else
    {
        return history.back();
    }
}

void MainWindow::nukeHistory()
{
    history.clear();
}
